﻿using System.Globalization;
using System.Threading;
using System.Web.Mvc;
using FoodBank.Web.Helpers;

namespace FoodBank.Web.Controllers
{
    public class BaseController : Controller
    {
        /// <summary>
        /// Called before the action method is invoked.
        /// </summary>
        /// <param name="filterContext">Information about the current request and action.</param>
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            SetCulture();

            base.OnActionExecuting(filterContext);
        }

        private void SetCulture()
        {
            // Attempt to read the culture cookie from Request
            var cultureCookie = Request.Cookies["_culture"];
            var cultureName = cultureCookie != null ? cultureCookie.Value : Request.UserLanguages[0];

            // Validate culture name
            cultureName = CultureHelper.GetImplementedCulture(cultureName); // This is safe


            // Modify current thread's cultures            
            Thread.CurrentThread.CurrentCulture = new CultureInfo(cultureName);
            Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
        }
    }
}